package com.ruoyi.system.outto.game.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.mapper.AccountInfoMapper;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.core.OutUrlConstant;
import com.ruoyi.system.outto.core.RegionalCovert;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.IPXXXAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/20 14:07
 */
@Slf4j
@Service
public class PXXXApiImpl implements IPXXXAPI {

    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private AccountInfoMapper accountInfoMapper;
    @Autowired
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;
    private SalePartner salePartner;

    public static void main(String[] args) {
        String apiKey = "6a112ce0db7a07104e3ad9fa16d048a5";
        Map<String,Object> params = new HashMap<>();
        params.put("type","add");
        params.put("product_id","123");
        Map<String,Object> data = new TreeMap<>();
        data.put("name","测试");
        data.put("price","100");
        data.put("content","内容");
        data.put("image","图片");
        data.put("daqu","1");
        data.put("shuliang","10");
        long time = new Date().getTime();
        data.put("add_time",time);
        data.put("fangchenmi","0");


        data.put("shiming","0");
        data.put("apiKey",apiKey);

        StringBuffer resut = new StringBuffer();
        for (String key : data.keySet()) {
            System.out.println("key= "+ key + " and value= " + data.get(key));
            if (!"content".equals(key)){
                resut.append(data.get(key));
            }
        }
        System.out.println(resut);
        String sign = DigestUtils.sha1Hex(resut.toString());

        params.put("data",data);
        params.put("sign",sign);
        String shangjia_id = "zyl";
        params.put("shangjia_id",shangjia_id);
        params.put("unique_no_shangjia","1111");
        String paramsStr = JSONObject.toJSONString(params);
        String url = "http://api-shangjia.pxb7.com/api/product_wzry_v2.php";
        System.out.println("请求参数="+paramsStr);
        String res = HttpUtils.sendPost(url, paramsStr, "application/json");
        System.out.println("返回参数="+res);
        String message = JSONObject.parseObject(res).getString("message");
        String s = MapUntils.unicodeToString(message);
        System.out.println("返回参数="+s);
    }


    @Override
    public AjaxResult addGame(AccountInfo accountInfo,Long userId,SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = params(accountInfo,"add",salePartner);
        params.remove("apiKey");
        log.info("螃蟹添加接口请求参数={}",JSONObject.toJSONString(params));
        String url = "";


        if (Objects.equals("王者荣耀",accountInfo.getType())) {
            url = OutUrlConstant.PXXURL.replace("base","product_wzry_v2.php");
        }else if (Objects.equals("原神",accountInfo.getType())){
            url = OutUrlConstant.PXXURL.replace("base","product_yuanshen_v2.php");
        }else if (Objects.equals("和平精英",accountInfo.getType())){
            url = OutUrlConstant.PXXURL.replace("base","product_hpjy_v2.php");
        }else if (Objects.equals("英雄联盟",accountInfo.getType())){
            url = OutUrlConstant.PXXURL.replace("base","product_yxlm_v2.php");
        }else{
            throw new GlobalException("螃蟹暂不支持此游戏");
        }


        String response = HttpUtils.sendPost(url, JSONObject.toJSONString(params),"application/json");
        log.info("螃蟹添加接口返回参数={}",response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String message = resultJson.getString("message");
        message = MapUntils.unicodeToString(message);

        Map<String, Object> result = new HashMap<>();
        if (!"200".equals(resultJson.getString("code"))){
            result.put("code",500);
        }else {
            result.put("code",200);
        }

        result.put("req",JSONObject.toJSONString(params));
        result.put("res",response);
        result.put("msg",message);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(AccountInfo accountInfo,Long userId,SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = params(accountInfo,"update",salePartner);
        params.remove("apiKey");
        log.info("螃蟹编辑接口请求参数={}",JSONObject.toJSONString(params));
        String url = "";
        if (Objects.equals("王者荣耀",accountInfo.getType())) {
            url = OutUrlConstant.PXXURL.replace("base","product_wzry_v2.php");
        }else if (Objects.equals("原神",accountInfo.getType())){
            url = OutUrlConstant.PXXURL.replace("base","product_yuanshen_v2.php");
        }else if (Objects.equals("和平精英",accountInfo.getType())){
            url = OutUrlConstant.PXXURL.replace("base","product_hpjy_v2.php");
        }else if (Objects.equals("英雄联盟",accountInfo.getType())){
            url = OutUrlConstant.PXXURL.replace("base","product_yxlm_v2.php");
        }else{
            throw new GlobalException("螃蟹暂不支持此游戏");
        }

        String response = HttpUtils.sendPost(url, JSONObject.toJSONString(params),"application/json");
        log.info("螃蟹编辑接口返回参数={}",response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String message = resultJson.getString("message");
        message = MapUntils.unicodeToString(message);
        Map<String, Object> result = new HashMap<>();
        if (!"200".equals(resultJson.getString("code"))){
            result.put("code",500);
        }else {
            result.put("code",200);
        }
        result.put("req",JSONObject.toJSONString(params));
        result.put("res",response);
        result.put("msg",message);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult delGame(Long id,Long userId,SalePartner salePartner) {

        String url = "";
        AccountInfo accountInfo = accountInfoMapper.selectAccountInfoById(id);
        if (null != accountInfo){

            if (Objects.equals("王者荣耀",accountInfo.getType())) {
                url = OutUrlConstant.PXXURL.replace("base","product_wzry_v2.php");
            }else if (Objects.equals("原神",accountInfo.getType())){
                url = OutUrlConstant.PXXURL.replace("base","product_yuanshen_v2.php");
            }else if (Objects.equals("和平精英",accountInfo.getType())){
                url = OutUrlConstant.PXXURL.replace("base","product_hpjy_v2.php");
            }else if (Objects.equals("英雄联盟",accountInfo.getType())){
                url = OutUrlConstant.PXXURL.replace("base","product_yxlm_v2.php");
            }else{
                throw new GlobalException("螃蟹暂不支持此游戏");
            }

            Map<String,Object> params = new HashMap<>();
            params.put("type","delete");
            params.put("product_id",id);


            StringBuffer resut = new StringBuffer();
            for (String key : params.keySet()) {
                if (!"content".equals(key)){
                    resut.append(params.get(key));
                }
            }
            String sign = salePartner.getSaleKey()+id;
            sign = DigestUtils.sha1Hex(sign);
            params.put("sign",sign);

            params.put("unique_no_shangjia",id);
            params.put("shangjia_id",salePartner.getOther());
            log.info("螃蟹删除接口请求参数={}",JSONObject.toJSONString(params));
            String response = HttpUtils.sendPost(url, JSONObject.toJSONString(params),"application/json");
            log.info("螃蟹删除接口返回参数={}",response);
            JSONObject resultJson = JSONObject.parseObject(response);
            String message = resultJson.getString("message");
            message = MapUntils.unicodeToString(message);
            Map<String, Object> result = new HashMap<>();
            if (!"200".equals(resultJson.getString("code"))){
                result.put("code",500);
            }else {
                result.put("code",200);
            }
            result.put("req",JSONObject.toJSONString(params));
            result.put("res",response);
            result.put("msg",message);
            return AjaxResult.success(result);
        }else {
            throw new GlobalException("删除ID未查询到此数据");
        }
    }

    private Map<String, Object> params(AccountInfo accountInfo,String type,SalePartner sa){

        Map<String,Object> params = new HashMap<>();
        params.put("type",type);
        params.put("product_id",String.valueOf(accountInfo.getId()));
        Map<String,Object> data = new TreeMap<>();
        data.put("name","【"+descTitle + "_" + accountInfo.getId() + "】 " + accountInfo.getLevel() + "  " +accountInfo.getDes());

        if (accountInfo.getPrice().compareTo(new BigDecimal(1000)) < 0){
            throw new GlobalException("价格太低，不推送");
        }else {
            BigDecimal bigDecimal = commonApi.addPrice(accountInfo.getPrice(), sa.getSeleep());
            commonApi.setPrice(bigDecimal,accountInfo.getId(),sa);
            data.put("price",bigDecimal);
        }


        StringBuffer imgs = new StringBuffer();
        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        if (!CollectionUtils.isEmpty(infoImgs)){
            for (InfoImg img : infoImgs) {
                String imgStr = img.getImgUrl()+" ";
                imgs.append("<img src="+imgStr+"/>");
            }
        }
        String content = "<h3>" + accountInfo.getDes() + "</h3>";
        data.put("content",content+imgs.toString());
        String titleImg = accountInfo.getTitleImg();
        if (!StringUtils.isNull(titleImg)){
            data.put("image",titleImg);
        }else if(!org.springframework.util.CollectionUtils.isEmpty(infoImgs)){
            data.put("image",infoImgs.get(0).getImgUrl());
        }else {
            data.put("image",this.salePartner.getTwoOther());
        }

        if (Arrays.asList(LCConstant.CoverGames).contains(accountInfo.getType())){
            String regional = RegionalCovert.toPX(accountInfo.getRegional());
            if (StringUtils.isEmpty(regional)){
                throw new GlobalException("大区转换失败，当前系统大区是" + accountInfo.getRegional());
            }
            data.put("daqu",regional);

            /**
             *   0 皮肤数量50以下    
             *         1 皮肤数量51-100
             *         2 皮肤数量101-150
             *         3 皮肤数量151-200
             *         4 皮肤数量201-250
             *         5 皮肤数量251-300
             *         6 皮肤数量301-311
             */

            Integer skins = accountInfo.getSkins();
            if (null == skins) skins = 0;
            if (Objects.isNull(skins)){
                skins = accountInfo.getGuns();
                if (Objects.isNull(skins)){
                    skins = 0;
                }
            }
            if (skins < 50){
                data.put("shuliang","0");
            }else if (50 < skins && skins <= 100){
                data.put("shuliang","1");
            }else if (100 < skins && skins <= 150){
                data.put("shuliang","2");
            }else if (150 < skins && skins <= 200){
                data.put("shuliang","3");
            }else if (200 < skins && skins <= 250){
                data.put("shuliang","4");
            }else if (250 < skins && skins <= 300){
                data.put("shuliang","5");
            }else if (300 < skins && skins <= 311){
                data.put("shuliang","6");
            }else {
                data.put("shuliang","6");
            }
            data.put("fangchenmi","0");
            if (Arrays.asList(LCConstant.haveTwoList).contains(accountInfo.getLevel())){
                data.put("shiming","0");
            }else {
                data.put("shiming","1");
            }
        }else {
           /* 1  bilibili服
            2   mihoyo服
            6、youxiangshiming*/

            data.put("daqu","2");
            data.put("youxiangshiming","1");
        }
        long time = DateUtils.getNowDate().getTime();
        data.put("add_time",time/1000);
        data.put("apiKey",this.salePartner.getSaleKey());

        StringBuffer resut = new StringBuffer();
        for (String key : data.keySet()) {
            if (!"content".equals(key)){
                resut.append(data.get(key));
            }
        }
        String sign = DigestUtils.sha1Hex(resut.toString());
        params.put("sign",sign);

        data.remove("apiKey");
        params.put("data",data);
        params.put("shangjia_id",this.salePartner.getOther());
        params.put("unique_no_shangjia",String.valueOf(accountInfo.getId()));
        return params;
    }
}

